#ifndef SQLQUERY_H
#define SQLQUERY_H

#include"sqlite3.h"
//#include"server.h"
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cstring>
#include<sstream>
#include<vector>

#define RemarkSize 20
#define InitContentSize 100

typedef unsigned short ushort;

struct ContentList;
using namespace std;

struct ContentList{
    ushort FoodNum;
    ushort FoodSum;
    char Remark[RemarkSize];
    ContentList *next;
    ContentList *pre;
};

string itoa(ushort num){
    stringstream ss;
    ss<<num;

    return ss.str();
}

class SqlResult{
    private:
    public:
	SqlResult(){
	    List=new ContentList;
	    GetMemery();
	    col=0;
	    rol=0;
	}
	~SqlResult(){}

	void GetMemery(){
	    int n=0;
	    ContentList *p=List;
	    while(n++<InitContentSize){
		ContentList *p1=new ContentList;
		p->next=p1;
		p1->pre=p;
		p=p->next;
	    }
	    
	}

	void show(){
	    cout<<"rol="<<rol<<endl;
	    cout<<"col="<<col<<endl;
	    for(int i=0;i<=rol;++i){
		for(int j=0;j<col;++j){
		    printf("tb[%d]=%s  ",i*col+j,tb[i*col+j]);
		}
		cout<<endl;
	    }
	}
	ContentList* GetResult(){
	    ContentList *p=List;
	    ContentList *Pfree=p;
	    for(int i=1;i<=rol;++i){
		p->FoodNum=atoi(tb[i*col]);
		strcpy(p->Remark,tb[i*col+1]);
		if(col==3){
		    p->FoodSum=atoi(tb[i*col+2]);
		}else{
		    p->FoodSum=0;
		}
		Pfree=p;
		p=p->next;
	    }
	
	    Pfree->next=NULL;
	    if(rol==0){
		delete p;
		return NULL; 
	    }else{
		delete p;
		return List;
	    }
	}
    public:
	char **tb;
	ContentList *List;
	
	int col;
	int rol;
};

class SqlQuery{
    public:
	SqlQuery(){}

	~SqlQuery(){}

	bool open(string path){
	    if(!sqlite3_open(path.c_str(),&pdb))return true;return false;
	}
	bool close(){
	    if(!sqlite3_close(pdb))return true;
	    return false;
	}
	bool exec(string sql){
	    if(!sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL))return true;
	    return false;
	}

	SqlResult Query(string sql){
	    table=new SqlResult();
	    sqlite3_get_table(pdb,sql.c_str(),&table->tb,&table->rol,&table->col,NULL);
	    sqlite3_free_table(table->tb);
	    return *table;

	}
    private:
	sqlite3 *pdb=NULL;
	SqlResult *table;
};
#endif
